package cn.bsuc.crm.service.impl;


import cn.bsuc.crm.entity.Permission;
import cn.bsuc.crm.entity.Role;
import cn.bsuc.crm.mapper.PermissionMapper;
import cn.bsuc.crm.mapper.RoleMapper;
import cn.bsuc.crm.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;



@Service
public class RoleServiceImp extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    @Transactional
    public int saveRole(Role role) {
        LocalDateTime now = LocalDateTime.now();
        if (role.getId() == null){
           role.setCreateDate(now);
            role.setUpdateDate(now);
            int insert = baseMapper.insert(role);
            if (insert==1){
                return 1;
            }else {return 0;}
        }else {
            QueryWrapper<Role> objectQueryWrapper = new QueryWrapper<>();
            objectQueryWrapper.eq("id",role.getId());
            role.setUpdateDate(now);
            int update = baseMapper.update(role, objectQueryWrapper);
            if (update==1){
                return 1;
            }else {return 0;}
            }
        }

    @Override
    public Page<Role> selectAllrole(Integer pageNo, Integer pageSize) {
        Page<Role> objectPage = new Page<>(pageNo, pageSize);
        Page<Role> userPage = baseMapper.selectPage(objectPage, null);
        return userPage;
    }

    @Override
    public int deleteRoleAndPermission(Integer roleId) {
        int i = baseMapper.deleteById(roleId);
        System.out.println(i);
        QueryWrapper<Permission> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("role_id",roleId);
        int delete = permissionMapper.delete(objectQueryWrapper);
        if (i>=1&&delete>=0){
            return 1;
        }
        return 0;
    }
}
